#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
FlaSam Code

2007 2007-6-26 上午11:25:40
'''

from ad_decorators import check_role, check_roles
from apps.ad_manager.models import AdItemInfo
from apps.ad_manager.models import AdOrganize, AdOrganizeInfo
from apps.ad_usergroup.ad_usergroup_views import creator_protect
from apps.ad_usergroup.ad_usergroup_views import flash
from apps.ad_usergroup.models import AdPlace
from apps.ad_usergroup.models import AdPlayerInfo
from django import newforms as forms
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.context_processors import request
from django.db import transaction, IntegrityError
from django.http import Http404
from django.http import HttpResponse, HttpResponseRedirect
from django.newforms import form_for_fields, form_for_model, form_for_instance
from django.shortcuts import render_to_response
from django.template import Context, Template, loader, RequestContext
from django.views.decorators.cache import cache_control
from django.views.generic.create_update import create_object
from django.views.generic.create_update import update_object
from django.views.generic.list_detail import object_detail, object_list
from utils import ad_utils

# Create your views here.

@login_required
def index(request):

    if request.user.is_authenticated():
        return HttpResponseRedirect('/news/')
    else:
        return HttpResponseRedirect('/accounts/login/')
    #return HttpResponse('Index')
    
def error_permission(request):
    '''
    error permissions , just return http 404 code
    @param request:
    '''
    return render_to_response('error_permission.html')

@check_roles(('corp_administrators', 'corp_managers', 'corp_users', 'province_agents', 'city_agents', 'place_agents'))
def adorg_list(request):
    
    adorg_obj = AdOrganizeInfo.objects.all().order_by('-last_modify_datetime') #@UndefinedVariable
    
    e_c = {}
    
    return object_list(request, queryset=adorg_obj, template_name='adorg_list.html', extra_context=e_c, paginate_by=30)

@check_roles(('corp_administrators', 'corp_managers'))
def adorg_delete(request, i):
    
    adorg_info_obj = AdOrganizeInfo.objects.get(id=i) #@UndefinedVariable
    
    # check creator protect
    if creator_protect(request.user, adorg_info_obj):
        pass
    else:
        return HttpResponseRedirect('/error_permission/')
    
    
    #adorg_obj = AdOrganize.objects.get(info=i) #@UndefinedVariable
    
    adorg_info_obj.delete()
    
    #adorg_obj.delete()
    
    return HttpResponseRedirect('/adorg/')
    
    
@check_roles(('corp_administrators', 'corp_managers', 'corp_users', 'province_agents', 'city_agents', 'place_agents'))
@cache_control(no_cache=True)
#@transaction.commit_manually
def adorg_create(request):
    
    _adorg_form = form_for_model(AdOrganize, fields=['users', 'places'])
    _adorg_info_form = form_for_model(AdOrganizeInfo, fields=['adorg_desc'])
    
    class AdOrgForm(forms.Form):
        
        adorg_users = forms.ModelMultipleChoiceField(label='用户', help_text='按住Ctrl允许多选', required=False, queryset=AdPlayerInfo.objects.all()) #@UndefinedVariable
        adorg_places = forms.ModelMultipleChoiceField(label='区域', help_text='按住Ctrl允许多选', required=False, queryset=AdPlace.objects.all()) #@UndefinedVariable
        adorg_desc = forms.CharField(label='说明', required=False, help_text='特殊编组的说明, 系统仍然会生成自动的描述,该字段不受到影响', widget=forms.Textarea())
        
        def clean(self):
            p = self.cleaned_data['adorg_places']
            u = self.cleaned_data['adorg_users']
            _hash = ad_utils.mk_name_space_uuid('%s%s' % (u, p))
            
            try:
                AdOrganizeInfo.objects.get(adorg_uuid=_hash) #@UndefinedVariable
            except AdOrganizeInfo.DoesNotExist: #@UndefinedVariable
                return self.cleaned_data
            else:
                raise forms.ValidationError('重复的广告编组')
        
        def save(self):
            adorg_info_obj = AdOrganizeInfo()
            adorg_info_obj.save()
            adorg_obj = AdOrganize(info=adorg_info_obj)
            adorg_obj.save()
            for x in self.cleaned_data['adorg_users']:
                adorg_obj.users.add(x)
            for x in self.cleaned_data['adorg_places']:
                adorg_obj.places.add(x)
            adorg_obj.flush_adorg_info()
    
    a_form = AdOrgForm
    
    t = loader.get_template('adorg_create.html')
    
    if request.method == 'GET':
    
        e_c = {
              'adorg_form':a_form(), \
              'request':request
                }
        
        c = Context(e_c)
        
        return HttpResponse(t.render(c))
    
    elif request.method == 'POST':
        
        adorg_form_res = a_form(request.POST)
        
        if adorg_form_res.is_valid():
            adorg_form_res.save()
            return HttpResponseRedirect('/adorg/')
        else:
            e_c = {
              'adorg_form':adorg_form_res, \
              'request':request
                }
        
            c = Context(e_c)
            return HttpResponse(t.render(c))

    else:
        pass


@check_roles(('corp_administrators', 'corp_managers', 'corp_users', 'province_agents', 'city_agents', 'place_agents'))
# i don't want to cache middleware cache this view page
@cache_control(no_cache=True)
@transaction.commit_manually
def adorg_detail(request, i):
    
    #FIXME: should use forms's clean , to check uuid
    # get AdOrgnaizeInfo's QuerySet
    adorg_info_qs_obj = AdOrganizeInfo.objects.all() #@UndefinedVariable
    
    # get adorg info obj by i
    adorg_info_obj = AdOrganizeInfo.objects.get(id=i) #@UndefinedVariable
    
    # get adorg obj
    adorg_obj = AdOrganize(info=adorg_info_obj)
    
    # check creator protect
    if creator_protect(request.user, adorg_info_obj):
        pass
    else:
        return HttpResponseRedirect('/error_permission/')
    
    # OK make form from instance
    _adorg_info_form = form_for_instance(adorg_info_obj, fields=['adorg_desc'])
    _adorg_form = form_for_instance(adorg_obj, fields=['users', 'places'])
    
    class AdOrgnaizeFrom(_adorg_form):
        '''
        make a custom adorg_form
        '''
        pass
            
    class AdOrgnaizeInfoForm(_adorg_info_form):
        pass
    
    adorg_form = AdOrgnaizeFrom
    adorg_info_form = AdOrgnaizeInfoForm
    
    if request.method == 'GET':
        e_c = {
              'adorg_form':adorg_form, \
              'adorg_info_form':adorg_info_form
                }
        return object_detail(request, queryset=adorg_info_qs_obj, object_id=i, template_name='adorg_detail.html', extra_context=e_c)

    elif request.method =='POST':
        
        adorg_res = adorg_form(request.POST)
        adorg_info_res = adorg_info_form(request.POST)
        
        if adorg_res.is_valid() and adorg_info_res.is_valid():
            adorg_info_res.save()
            adorg_res.save()
            try:
                adorg_obj.flush_adorg_info()
            except IntegrityError:
                transaction.rollback()
            else:
                transaction.commit()
                
            return HttpResponseRedirect('/adorg/%s' % i)
        else:
            e_c = {
              'adorg_form':adorg_res, \
              'adorg_info_form':adorg_info_res
                }
            
            return object_detail(request, queryset=adorg_info_qs_obj, object_id=i, template_name='adorg_detail.html', extra_context=e_c)
    else:
        pass

    
@check_roles(('corp_administrators', 'corp_managers', 'corp_users', 'province_agents', 'city_agents', 'place_agents'))
def aditem_list(request):
    aditem_obj_qs = AdItemInfo.objects.all() #@UndefinedVariable
    
    e_c = {}
    
    return object_list(request, queryset=aditem_obj_qs, template_name='aditem_list.html', extra_context=e_c, paginate_by=30)
    

@check_roles(('corp_administrators', 'corp_managers', 'corp_users', 'province_agents', 'city_agents', 'place_agents'))
def aditem_detail(request, i):
    
    aditem_info_obj = AdItemInfo.objects.get(id=i) #@UndefinedVariable
    
    # check creator protect
    if creator_protect(request.user, aditem_info_obj):
        pass
    else:
        return HttpResponseRedirect('/error_permission/')
    
    if request.user.has_perm('ad_manager.can_approve_aditem.can_vote'):
        _aditem_info_form = form_for_instance(aditem_info_obj, fields=[
                                                                       'ad_item_name', \
                                                         'ad_item_desc', \
                                                         'ad_item_display_interval', \
                                                         'ad_item_desc', \
                                                         'ad_item_useable', \
                                                         'ad_item_start_date', \
                                                         'ad_item_expire_date'])
    else:
        _aditem_info_form = form_for_instance(aditem_info_obj, fields=[
                                                                       'ad_item_name', \
                                                         'ad_item_desc', \
                                                         'ad_item_display_interval', \
                                                         'ad_item_desc', \
                                                         'ad_item_start_date', \
                                                         'ad_item_expire_date'])
    
    class AdItemInfoForm(_aditem_info_form):
        
        def clean_ad_item_expire_date(self):
            s_date = self.cleaned_data['ad_item_start_date']
            e_date = self.cleaned_data['ad_item_expire_date']
            if (e_date-s_date).days < 1:
                raise forms.ValidationError('广告的结束时间不能晚于开始时间')
            return self.cleaned_data['ad_item_expire_date']
    
    t = loader.get_template('aditem_detail.html')
    
    if request.method == 'GET':
        e_c = {'request':request, \
               'aditem_info_form': AdItemInfoForm(), \
                'object':aditem_info_obj
                }
    
        c = Context(e_c)
    
        return HttpResponse(t.render(c))
    elif request.method =='POST':
        
        u = AdItemInfoForm(request.POST)
        
        if u.is_valid():
            u.save()
            return HttpResponseRedirect('/aditem/%s/' % i)
        else:
            e_c = {'request':request, \
                   'aditem_info_form': u, \
                    'object':aditem_info_obj
                    }
    
            c = Context(e_c)
        
            return HttpResponse(t.render(c))
    
@check_roles(('corp_administrators', 'corp_managers', 'corp_users', 'province_agents', 'city_agents', 'place_agents'))
def aditem_content_detail(request, i):
    aditem_info_obj = AdItemInfo.objects.get(id=i) #@UndefinedVariable
    
    # check creator protect
    if creator_protect(request.user, aditem_info_obj):
        pass
    else:
        return HttpResponseRedirect('/error_permission/')
    
    aditem_obj = aditem_info_obj.get_item()
    
    _aditem_content_obj_form = form_for_instance(aditem_obj)
    
    class AdItemContentFrom(_aditem_content_obj_form):
        pass
    
    t = loader.get_template('aditem_content_detail.html')

    AdItemContentFrom.base_fields['ad_item_name'].widget = forms.HiddenInput()

    if request.method == 'GET':
        e_c = {'request':request, \
               'object':aditem_info_obj, \
               'aditem_content_form': AdItemContentFrom()
               }
    
        c = Context(e_c)
    
        return HttpResponse(t.render(c))
    elif request.method == 'POST':
        
        if aditem_info_obj.get_protocol() == 'wallpaper':
            u = AdItemContentFrom(request.POST, request.FILES)
        else:
            u = AdItemContentFrom(request.POST)
        
        if u.is_valid():
            u.save()
            return HttpResponseRedirect('/aditem/%s/content/' % i)
        else:
            e_c = {'request':request, \
               'object':aditem_info_obj, \
               'aditem_content_form': u
               }
    
            c = Context(e_c)
    
            return HttpResponse(t.render(c))

@check_roles(('corp_administrators', 'corp_managers', 'corp_users', 'province_agents', 'city_agents', 'place_agents'))
def aditem_change_state(request, i):
    aditem_info_obj = AdItemInfo.objects.get(id=i) #@UndefinedVariable
    
    # check creator protect
    if creator_protect(request.user, aditem_info_obj):
        pass
    else:
        return HttpResponseRedirect('/error_permission/')
    
    if aditem_info_obj.ad_item_useable:
        aditem_info_obj.ad_item_useable = False
        aditem_info_obj.save()
    else:
        aditem_info_obj.ad_item_useable = True
        aditem_info_obj.save()
    
    return HttpResponseRedirect('/aditem/')

@check_roles(('corp_administrators', 'corp_managers', 'corp_users', 'province_agents', 'city_agents', 'place_agents'))
def aditem_create(request):
    
    _aditem_info_form = form_for_model(AdItemInfo, fields=['ad_item_name', \
                                                          'ad_item_desc', \
                                                          'ad_item_protocol', \
                                                          'ad_item_display_interval', \
                                                          'ad_item_start_date', \
                                                          'ad_item_expire_date'])
    
    class AdItemInfoForm(_aditem_info_form):
        pass
    
    t = loader.get_template('aditem_create.html')
    
    e_c = {'request':request, \
           'aditem_form':AdItemInfoForm()
           }
    
    c = Context(e_c)
    
    
    #adite_conten_form = form_for_model(adite, form, fields, formfield_callback)
    return HttpResponse(t.render(c)) 

    
    
      
